<template>
<div>
    <el-card shadow="hover">
        <el-form :inline="true" :model="searchStudent">
            <el-form-item label="姓名：" >
                <el-input v-model="searchStudent.name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="年龄：">
                <el-input  type="number" v-model="searchStudent.age" placeholder="请输入年龄" clearable/>
            </el-form-item>
            <el-form-item label="班级：">
                <el-select v-model="searchStudent.sclass" placeholder="请选择班级" clearable="">
                    <el-option
                      v-for="item in classList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.name">
                    </el-option>
                  </el-select>
            </el-form-item>
             <el-form-item >
                <el-button type="primary" plain @click="search">查询</el-button>
             </el-form-item>
             <el-form-item >
               <el-button type="primary" @click="openAddDialog">添加学生</el-button>
             </el-form-item>
             <el-form-item >
              <el-button type="danger" @click="openDeleteBatchDialog">批量删除</el-button>
            </el-form-item>
             <el-dialog
                :close-on-click-modal="true"
                :title="title"
                :visible.sync="addDialog"
                width="30%"
                :before-close="handleClose">
                <el-form :model="addStudent" :rules="rules" ref="form" >
                    <el-form-item label="姓名："  prop="name">
                        <el-input v-model="addStudent.name" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="年龄：" prop="age">
                        <el-input v-model.number="addStudent.age" placeholder="请输入年龄"></el-input>
                    </el-form-item>  
                    <el-form-item label="电话：" prop="phone">
                        <el-input v-model="addStudent.phone"  maxlength="11" type="number" placeholder="请输入电话"></el-input>
                    </el-form-item>
                    <el-form-item label="班级：" prop="sclass" >
                        <el-select v-model="addStudent.sclass" placeholder="请选择班级">
                            <el-option
                              v-for="item in classList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.name">
                            </el-option>
                          </el-select>
                    </el-form-item> 
                </el-form>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialog = false">取 消</el-button>
                    <el-button type="primary" @click="confirm">确 定</el-button>
                  </span>
            </el-dialog>
        </el-form>
        <el-table
            :data="studentList"
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
          <el-table-column
              label="姓名"
              align="center"
              prop="name">
          </el-table-column>
          <el-table-column
              label="年龄"
              align="center"
              prop="age">
          </el-table-column>
          <el-table-column
              label="电话"
              align="center"
              prop="phone">
          </el-table-column>
          <el-table-column
              label="所在班级"
              align="center"
              prop="sclass">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  @click="openUpdateDialog(scope.$index, scope.row)">编辑</el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="openDeleteDialog(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
          <!-- 提示弹窗 -->
        <my-dialog :show="tipDialog" :message="tipMessage" :callBack="callBackFun" @close="closeFun" />
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
    </el-card>
</div>
</template>

<script>
import studentApi from '../api/StudentApi';
import MyDialog from './MyDialog.vue';
export default {
    name: 'student',
  props: {
    msg: String
  },
  data(){
    // 校验年龄规则
    var checkAge = (rule, value, callback) => {
        if (value == '') {
          return callback(new Error('年龄不能为空'));
        }
        if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
        if (value <1 || value >188) {
              callback(new Error('年龄输入范围错误'));
        } else {
              callback();
            }
        }
      };
    return{
      studentList: [],      // 当前页的所有学生信息集合
      classList:[],
      pageNo:1,               // 当前页
      pageSize:5,           // 每页大小
      total:100,            // 总记录数
      searchStudent:{
        name:"",
        sclass:"",
        age:null
      },
      title:'',
      addDialog:false,
      tipMessage:'', //删除提示
      tipDialog:false,//控制提示
      addStudent:{},
      callBackFun:{},
      deleteId:[],    //需要删除的id
      selectedList:[], //已选中的学生id
      rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                ],
                age: [
                  { required: true, message: '请输入年龄', trigger: 'blur' },
                  { validator: checkAge, trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { min: 11, max: 11, message: '请输入11位的电话号码', trigger: 'blur' }
                ],
                sclass: [
                    { required: true, message: '请输入班级', trigger: 'blur' },
                ],
         }
    }
  },
  async created(){
   this.loadList()
   let {data} = await  studentApi.selectAllClass();
   this.classList = data;
   
  },
  methods: {
    // 打开批量删除对话框
    openDeleteBatchDialog(){
      if(this.deleteId.length == 0){
        this.$message.error('请选择学生！');
        return
      }
      this.tipMessage = `确认要删除这些数据吗？`
      this.tipDialog = true;
      this.callBackFun = this.deleteStudent;
    },
    // 选择信息改变
    handleSelectionChange(val){
     this.deleteId = val.map(item => item.id);     
    },
    // 打开新增学生对话框
    openAddDialog(){
      this.title = "新增学生信息";
      this.addDialog = true;
    },
    // 打开更新学生对话框
    openUpdateDialog(index,data){
      this.title = "修改学生信息";
      this.addDialog = true;
      this.addStudent = data;
    },
    //打开删除学生对话框
    openDeleteDialog(index,row){
      this.tipMessage = `确认要删除${row.name}吗？`
      this.tipDialog = true;
      this.callBackFun = this.deleteStudent;
      this.deleteId.splice(0,this.deleteId.length);
      this.deleteId.push(row.id);
    },
    // 模糊查找
    async search(){
      this.pageNo = 1;  
      let {data} = await studentApi.selectByCondition(this.pageNo,this.pageSize,this.searchStudent)
      this.total=data.total;
      this.studentList = data.rows; 
    },
    // 修改学生实现
    async updateStudent(){
      let {data} = await studentApi.updateStudent(this.addStudent);
      this.showTips(data);
    },
    // 新增学生实现
    async addStudentFun(){
      let {data} = await studentApi.addStudent(this.addStudent);
      this.showTips(data);
    },
     // 删除学生函数
    async deleteStudent(){
      let {data} =  await studentApi.deleteById(this.deleteId);
      this.showTips(data);
      this.loadList()
    },
    // 对话框确认函数
    confirm(){
      this.$refs.form.validate(valid => {
      if(valid){
        if(this.addStudent.id != null){
          this.updateStudent()
        }else{
          this.addStudentFun()
        }
      }else return;
      })
    },
    // 每页大小改变时事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadList();
    },
    // 当前页改变时事件
    handleCurrentChange(val) {
      this.pageNo = val;
      this.loadList();
    },
    // 加载数据
    async loadList(){
      let {data} = await studentApi.selectByCondition(this.pageNo,this.pageSize,this.searchStudent);
      this.studentList = data.rows;
      this.total = data.total;
      console.log(data)        
    },
    // 关闭对话框函数
    closeFun(val){     
      this.tipDialog = val;
    },
    handleClose(){
      this.addDialog = false;
    },
    // 显示后端相应信息
    showTips(data){
      if(data.code == 200){
            this.$message({
              type:'success',
              message:data.data,
              onClose:()=>{
                this.loadList();
                this.addDialog = false;
              }
            })
            this.addStudent = {};
        }else{
          this.$message({
              type:'error',
              message:data.data,
              onClose:()=>{
                this.loadList();
                this.addDialog = false;
              }
            })
        }
    }
  },
  components:{
    MyDialog,
  }

}
</script>

<style>
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>